<?php


namespace app\api\controller\v1;
use app\exception\OrderException;
use app\exception\TokenException;
use app\validate\api\IDMustBePositiveInt;
use app\validate\api\OrderPlace;
use app\api\service\Token as TokenService;
use app\validate\api\PagingParameter;
use think\annotation\Route;
use think\annotation\route\Middleware;
use think\Exception;
use app\api\service\Order as OrderService;
use app\api\model\Order as OrderModel;


class Order
{
    // 用户在选择商品后，向API提交包含它所选择商品的相关信息
    // API 在接收 到信息后，需要检查订单相关商品的库存量
    //  有库存，把订单数据存入数据库中，下单成功，返回客户端信息，告诉客户端可以支付了
    // 调用我们的支付接口，进入支付
    // 还需要再次进行库存量检测
    // 服务器这边就可以调用微信支付接口进行支付
    // 小程序根据服务器返回的结果拉起微信支付
    // 微信会返回给我们一个支付结果 （异步）
    // 成功:也需要进行库存量的检查
    // 成功，进行库存量扣除

    /**
     * @return mixed
     * @throws Exception|\http\Exception
     */
    public function placeOrder()
    {
        (new OrderPlace())->goCheck();
        $products = input('post.products/a');
        $uid = TokenService::getCurrentID();

        $order = new OrderService();
        $status = $order->place($uid,$products);
        return json($status);
    }

    /**
     * @param     $page
     * @param int $size
     * @Route("v1/order/by_user",method="get")
     * @Middleware(\app\middleware\api\checkPrimaryScope::class)
     * @return array|false|string
     * @throws Exception
     * @throws TokenException
     *
     */
    public function getSummaryByUser($page=1,$size =1)
    {
        (new PagingParameter())->goCheck();
        $uid = TokenService::getCurrentID();
        $pagingOrders = OrderModel::getSummaryByUser($uid,$page,$size);
        if($pagingOrders->isEmpty()){
            return json([
                'data' => [],
                'current_page' => $pagingOrders->getCurrentPage()
            ]);
        }
        return json([
            'data' => $pagingOrders->hidden(['snap_items','snap_address','prepay_id','user_id','delete_time','update_time'])->toArray(),
            'current_page' => $pagingOrders->getCurrentPage()
        ]);
    }

    /**
     * @param $id
     *
     * @return \think\response\Json
     * @throws Exception
     * @throws OrderException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDetail($id){
        (new IDMustBePositiveInt())->goCheck();
        $orderDetail = OrderModel::find($id);
        if($orderDetail->isEmpty()){
            throw new OrderException();
        }
        return json($orderDetail->hidden(['user_id','delete_time','update_time','prepay_id']));
    }
}